﻿using WpfMvvmTemplatePrismHC.Common;
using WpfMvvmTemplatePrismHC.Models.BindingModels;
using WpfMvvmTemplatePrismHC.Models.ProgramModel;
using WpfMvvmTemplatePrismHC.Tools.Events;

namespace WpfMvvmTemplatePrismHC.ViewModels.UserControls
{
    public class ViewBViewModel : BindableBase, IConfirmNavigationRequest
    {
        /// <summary>
        /// ViewBModel模型
        /// </summary>
        public ViewBModel? ViewBModels { get; set; }

        private readonly IEventAggregator? eventAggregator;
        public IContainerProvider? containerProvider { get; }
        public DelegateCommand? PublishCommand { get; set; }

        public ViewBViewModel()
        {
            ViewBModels = GlobalStaticData.IsDesignTime ? new ViewBModel() : containerProvider.Resolve<ProgramModel>().ViewBModels;
        }

        public ViewBViewModel(IContainerProvider containerProvider, IEventAggregator eventAggregator)
        {
            ViewBModels = GlobalStaticData.IsDesignTime ? new ViewBModel() : containerProvider.Resolve<ProgramModel>().ViewBModels;
            this.containerProvider = containerProvider;
            this.eventAggregator = eventAggregator;
            PublishCommand = new DelegateCommand(PublishEvent);
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        private void PublishEvent()
        {
            //测试从容器中获取数据
            //var container = containerProvider.Resolve<ProgramModel>().ViewAModels;

            //发布消息
            eventAggregator?.GetEvent<ValueChangedEvent<string>>().Publish(new ValueChangedEventArgs<string> { NewValue = ViewBModels?.Message });
        }


        /// <summary>
        /// 导航是否重用原来实例
        /// </summary>
        /// <param name="navigationContext"></param>
        /// <returns></returns>
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true; //是否重用原来实例，true为重用，表示不重新创建新实例
        }

        public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
        {
            //导航确认是在当前页面导航到其他页面时触发
            bool result = true;
            if (MessageBox.Show("确认导航吗？", "温馨提示：", MessageBoxButton.YesNo) == MessageBoxResult.No)
                result = false;

            continuationCallback(result);
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            if (navigationContext.Parameters.ContainsKey("Message"))
            {
                var message = navigationContext.Parameters["Message"];
            }
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }
    }
}